//
//  VideoViewController.m
//  GameBoss
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "VideoViewController.h"
#import "AFN_Get.h"
#import "VideoModel.h"
#import "VideoCollectionCell.h"
#import "UIImageView+WebCache.h"
#import "VideoDataViewController.h"
#import "UIScrollView+MJRefresh.h"

@interface VideoViewController ()

@property(nonatomic, retain)NSMutableArray *videoArr;
@property(nonatomic, retain)UICollectionView *videoCollection;
@property(nonatomic, retain)UISegmentedControl *videoSeg;
@property(nonatomic, assign)NSInteger page;

@end

@implementation VideoViewController

#pragma mark 查看self.navigationController的显示
//-(void)viewDidAppear:(BOOL)animated{
//    [super viewDidAppear:animated];
//    NSLog(@"%d",self.navigationController.navigationBarHidden);
//    NSLog(@"%@",self.navigationController);
//}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"视频";
        self.videoArr = [NSMutableArray array];
        self.page = 1;
    }
    return self;
}

-(void)videoData:(NSString *)strTemp :(NSString *)strSecondTemp :(NSInteger)page{
    
    NSString *strURL = [NSString stringWithFormat:@"http://api.3g.tudou.com/v4_3/channel/label_top?_e_=md5&guid=7066707c5bdc38af1621eaf94a6fe779&idfa=0B7202DD-B713-46CB-A45F-37BBA45115FC&module_id=%@&module_prot_id=%@&network=WIFI&operator=&ouid=ba203182df6eef9c3e9ba4f1591ea918e6e5d5a4&page_no=%ld&page_size=30&pid=c0637223f8b69b02&vdid=E3EA9151-C1F5-4A49-B5F0-D18A8450C139&ver=4.9.1", strTemp, strSecondTemp, page];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = [NSMutableArray array];
        arr = responseObject[@"items"];
        if (self.page == 1) {
            self.videoArr = [NSMutableArray array];
        }
        for (NSDictionary *temp in arr) {
            VideoModel *model = [[VideoModel alloc] init];
            [model setValuesForKeysWithDictionary:temp];
            [self.videoArr addObject:model];
            [model release];
        }
        [self.videoCollection reloadData];
#pragma mark 结束刷新
        [self.videoCollection headerEndRefreshing];
#pragma mark 结束加载
        [self.videoCollection footerEndRefreshing];
        
        if ((self.videoSeg.selectedSegmentIndex == 0) && (self.page == 1)) {
#pragma mark 数据库
#pragma mark 先删除表
            [[DataCache shareDataCache] dropTable:@"videoTable"];
#pragma mark 再创建表
            [[DataCache shareDataCache] createTable:@"videoTable"];
            for (int i=0; i<self.videoArr.count; i++) {
#pragma mark 添加model
                [[DataCache shareDataCache] insertModel:@"videoTable" model:self.videoArr[i]];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@", error);
#pragma mark 结束刷新
        [self.videoCollection headerEndRefreshing];
#pragma mark 结束加载
        [self.videoCollection footerEndRefreshing];
#pragma mark 解析失败得到缓存数据
        if (self.videoSeg.selectedSegmentIndex == 0) {
            self.videoArr = [[DataCache shareDataCache] selectModel:@"videoTable"];
            [self.videoCollection reloadData];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Screen.width, Screen.height)];
    imageView.image = [UIImage imageNamed:@"zaochen"];
    [self.view addSubview:imageView];
    [imageView release];

    //设置seg
    self.videoSeg = [[UISegmentedControl alloc] initWithItems:@[@"英雄联盟", @"魔兽世界3", @"电子竞技"]];
    self.videoSeg.frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
    [self.view addSubview:self.videoSeg];
    self.videoSeg.selectedSegmentIndex = 0;
    //加渲染色
    self.videoSeg.tintColor = [UIColor whiteColor];
    self.videoSeg.backgroundColor =  [UIColor colorWithRed:237/255.0 green:200/255.0 blue:0/255.0 alpha:1];
    
    //flowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(Screen.width*171/375, Screen.height*180/667);
    flowLayout.sectionInset = UIEdgeInsetsMake(Screen.width*10/375, Screen.height*10/667, Screen.width*10/375, Screen.height*10/667);
    
    self.videoCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height-153) collectionViewLayout:flowLayout];
    [self.view addSubview:self.videoCollection];
    self.videoCollection.backgroundColor = [UIColor clearColor];
    self.videoCollection.dataSource = self;
    self.videoCollection.delegate = self;
    //videoCollection设置乳白色
//    self.videoCollection.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:240/255.0];
    [_videoCollection release];
    

    [self.videoCollection registerClass:[VideoCollectionCell class] forCellWithReuseIdentifier:@"reuse"];
    
#pragma mark 夜间判断
    if ([NightMode shareNightMode].isNight) {
        [[NightMode shareNightMode] loadNightModeInfoFormDisk];
    }
    
    //刷新加载
    [self addHeader];
    [self addFooter];
    [self videoData:@"540" :@"124" :1];
    
#pragma mark 选择方法写在后面
    [self.videoSeg addTarget:self action:@selector(videoSegClick:) forControlEvents:UIControlEventValueChanged];
    [_videoSeg release];
}

-(void)videoSegClick:(UISegmentedControl *)videoSeg{
    self.page = 1;
    switch (videoSeg.selectedSegmentIndex) {
        case 0:
            [self videoData:@"540" :@"124" :1];
#pragma mark 偏移量为初始
            self.videoCollection.contentOffset = CGPointMake(0, 0);
            break;
        case 1:
            [self videoData:@"542" :@"109" :1];
            self.videoCollection.contentOffset = CGPointMake(0, 0);
            break;
        case 2:
            [self videoData:@"538" :@"130" :1];
            self.videoCollection.contentOffset = CGPointMake(0, 0);
            break;
        default:
            break;
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.videoArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    [cell.videoPic sd_setImageWithURL:[NSURL URLWithString:[self.videoArr[indexPath.row] picUrl_448x252]] placeholderImage:[UIImage imageNamed:@"iconfont-yonghutouxiang"]];
    cell.videostripe_b_r.text = [self.videoArr[indexPath.row] stripe_b_r];
    cell.videoTitle.text = [self.videoArr[indexPath.row] title];
    cell.videoPv.text = [NSString stringWithFormat:@"播放:%@", [self.videoArr[indexPath.row] pv]];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}
#pragma mark collection点击传值
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoDataViewController *videoDataVC = [[VideoDataViewController alloc] init];
    
    VideoModel *videoModel = self.videoArr[indexPath.row];;
    videoDataVC.itemUrl = videoModel.itemUrl;
    [self.navigationController pushViewController:videoDataVC animated:YES];
    [videoDataVC release];
}

#pragma mark 选取白黑两种模式
- (void)setNightDayModel {
//    [NightManager setBackgroundColorWithView:self.view];
//    [NightManager setBackgroundColorWithView:self.videoCollection];
    
}

- (void)setLightDayModel {
//    [NightManager setBackgroundColorWithView:self.view];
//    [NightManager setBackgroundColorWithView:self.videoCollection];
    
}
#pragma mark 上拉刷新
- (void)addHeader
{
    [self.videoCollection addHeaderWithCallback:^{
        self.page = 1;
        if (self.videoSeg.selectedSegmentIndex == 0) {
            [self videoData:@"540" :@"124" :1];
        }else if(self.videoSeg.selectedSegmentIndex == 1){
            [self videoData:@"542" :@"109" :1];
        }else{
            [self videoData:@"538" :@"130" :1];
        }
    }];
#pragma mark 第一次刷新需要
    [self.videoCollection headerBeginRefreshing];
}

#pragma mark 下拉加载
- (void)addFooter
{
    [self.videoCollection addFooterWithCallback:^{
        self.page ++;
        if (self.videoSeg.selectedSegmentIndex == 0) {
            [self videoData:@"540" :@"124" :self.page];
        }else if(self.videoSeg.selectedSegmentIndex == 1){
            [self videoData:@"542" :@"109" :self.page];
        }else{
            [self videoData:@"538" :@"130" :self.page];
        }
    }];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_videoArr release];
    [_videoCollection release];
    [_videoSeg release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
